﻿using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Threading.BackgroundWorkers;
using Abp.Threading.Timers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Order.Orders
{
    public class OrderPassiveWorker : PeriodicBackgroundWorkerBase, ISingletonDependency
    {
        private readonly OrderManager _orderManager;
        private readonly IRepository<Order> _orderRepository;

        public OrderPassiveWorker(AbpTimer timer, OrderManager orderManager, IRepository<Order> orderRepository )
           : base(timer)
        {
            _orderManager = orderManager;
            _orderRepository = orderRepository;
            Timer.Period = 1000 * 60 * 5;// 1000 * 60 * 60; //5 seconds (good for tests, but normally will be more)
        }

        [UnitOfWork]
        protected override void DoWork()
        {
            // 把超时的订单都取消掉
            DateTime temp = DateTime.Now.AddHours(-1);
            var items = _orderRepository.GetAll().Where(r =>
                r.Info.Status == Median.OrderStatus.Created
                && r.ShipInfo.ShipStatus == OrderShipStatus.PendingShip
                && r.PaymentInfo.PaymentStatus == OrderPaymentStatus.PendingPay
                && r.PaymentInfo.PaymentType == PaymentType.OnlinePayment
                && r.Info.CreationTime < temp).ToList();

            foreach(var item in items)
            {
                _orderManager.CancelOrder(item, "订单超时自动关闭").Wait();
            }
        }
    }
}
